import argparse
from pathlib import Path
import re
from collections import defaultdict
import shutil

parser = argparse.ArgumentParser(description = "生成注释shell")
parser.add_argument("-i", dest = "input_file", type = str, required = True)
parser.add_argument("-outdir", dest = "output_dir", type = str, required = True)
parser.add_argument("-db", dest = "database", type = str, nargs = '?')
args = parser.parse_args()
pydir = Path(__file__).parent
if args.database:
    database = args.database
else:
    database = pydir / 'card_kmer.fa'
input_file = args.input_file
outdir = Path(args.output_dir)
outdir_sh = outdir / 'shell'
if outdir_sh.exists() == False:
    outdir_sh.mkdir(parents = True)
seq_list = outdir/ 's2.blast.sh'
with open(input_file) as ifile, open(seq_list, 'w') as slist:
    for line in ifile:
        line = line.strip().split('\t')
        output = outdir_sh / f'{line[0]}.sh'
        slist.write(f'cd {outdir_sh}\nnohup sh {output} > {line[0]}.log 2>&1 &\n')
        with open(output, 'w') as oput:
             oput.write(f'''\
echo begin at: `date` && \\
cd {outdir} && \\
blastn -task megablast -query {line[1]} -db {database} -num_alignments 10 \
-max_hsps 1 -num_threads 18 -evalue 1e-10 \
-outfmt '6 qseqid sseqid pident length mismatch gapopen qlen qstart qend slen sstart send evalue bitscore staxid ssciname scomnitle sblastname sskingdom' \
-out {line[0]}.txt && \\
python3 {pydir}/s3.card_anno.py -i {line[0]}.txt -outdir {outdir} -s {line[0]} && \\
/home/yong_sun/bin/workflow/venv/bin/python {pydir}/s4.merge_gene_family.py -i {line[0]}.gene_mapping_data_bak.txt -o {line[0]}.gene_mapping_data.txt && \\
echo end at: `date`
''')
  
